package org.example.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.yc.damai.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.example.ZuulProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
public class DelayTokenFilter extends ZuulFilter {

    @Autowired
    LoginFilter loginFilter;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Autowired
    ZuulProperties zuulProperties;

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String servletPath = request.getServletPath();
        String regex = ".*/.*\\.html|.*/\\w+";
        return servletPath.matches(regex);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Cookie loginTokenCookie = null;
        if(request.getCookies() != null){
            for (Cookie cookie : request.getCookies()) {
                if(cookie.getName().equals("loginToken")){
                    loginTokenCookie = cookie;
                }
            }
        }
        if(loginTokenCookie != null){
            loginTokenCookie.setPath("/");
            loginTokenCookie.setMaxAge(60*30);
            context.getResponse().addCookie(loginTokenCookie);
        }
        return null;
    }
}
